package com.mender.user.controller.user;

import com.mender.common.constant.JwtClaimsConstant;
import com.mender.common.result.Result;
import com.mender.common.utils.JwtUtil;
import com.mender.user.domain.dto.UserLoginDTO;
import com.mender.domain.po.User;
import com.mender.user.domain.vo.UserLoginVO;
import com.mender.common.properties.JwtProperties;
import com.mender.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user/user")
@RestController
@Api(tags = "c端用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录:{}",userLoginDTO.getCode());
//        微信登录
        User user = userService.wxlogin(userLoginDTO);

//        为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @PostMapping("/getById")
    @ApiOperation("根据id获取用户信息")
    public Result<User> getById(Long id){
        return Result.success(userService.getById(id));
    }

    /**
     * 新增用户数 countNewUserByMap
     */
    @PostMapping("/countNewUser")
    @ApiOperation("新增用户数")
    public Result<Integer> countNewUserByMap(@RequestBody Map<String, Object> params){
        return Result.success(userService.countNewUserByMap(params));
    }


}
